<script setup>
import {onMounted, ref} from "vue";
import {deleteProduct, getProductList} from "@/api/product.js";
import CardArea from "@/components/cardArea.vue";
import MyTable from "@/common/myTable.vue";
import ProductForm from "@/views/product/product-form.vue";
import {ElMessage, ElMessageBox} from "element-plus";


const pageData = ref({
  list: [],
  total: undefined,
})
const id = ref(undefined)
const actionFlag = ref(false)
//搜索条件
const searchData = ref({
  page: 1,
  size: 10,
})

onMounted(async () => {
  await getList()
})

const getList = async () => {
  const {data} = await getProductList(searchData.value)
  pageData.value = data
}
const columns = [
  {key: 'selection', type: 'selection', width: '55px'},
  {key: 'id', title: 'id'},
  {key: 'name', title: '商品名称'},
  {key: 'description', title: '商品简介'},
  {key: 'image', title: '图片', type: 'img'},
  {key: 'status', title: '状态', slot: 'status'},
  {key: 'createdTime', title: '创建时间', width: '220px'},
  {key: 'updatedTime', title: '修改时间', width: '220px'},
  {key: 'action', title: '操作'},
]

// 删除
const del = (id) => {
  ElMessageBox.confirm('确定删除该商品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteProduct(id).then(res => {
      ElMessage.success('删除成功')
      getList()
    })
  })
}
</script>

<template>
  <!--表单操作处-->
  <el-dialog width="500" v-if="actionFlag" v-model="actionFlag" :before-close="() => {id=undefined;actionFlag = false}">
    <template #header>
      <div style="text-align: center;margin-bottom: 20px">
        <h1>{{ id ? '编辑商品' : '新增商品' }}</h1>
      </div>
    </template>
    <product-form :id="id" @success="() => {actionFlag = false;id=undefined;getList()}"/>
  </el-dialog>
  <card-area title="商品管理">
    <my-table v-model:search-data="searchData" :columns="columns" :list="pageData.list" :total="pageData.total"
              @load="getList">

      <template #created>
        <el-button theme @click="actionFlag = true">新增商品</el-button>
      </template>

      <template #status="{row}">
        <el-tag v-if="row.status === 1" type="success">启用</el-tag>
        <el-tag v-else type="danger">禁用</el-tag>
      </template>

      <template #action="{row}">
        <el-button type="warning" plain @click="() => {id = row.id;actionFlag = true}">编辑</el-button>
        <el-button type="danger" plain @click="del(row.id)">删除</el-button>
      </template>
    </my-table>
  </card-area>
</template>

<style scoped lang="scss">

</style>
